package com.matrix.draft.sockettest.day2;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {

    // 配置的属性
    private BIOProperties properties = new BIOProperties();

    // 线程池
    private ExecutorService pool = Executors.newCachedThreadPool();

    // IO处理器
    private ISocketHandler handler = new DefaultIOHandler();

    // 启动服务
    public void start(){
        try {
            // 开始监听
            ServerSocket serverSocket = new ServerSocket(properties.getPort());
            System.err.println("8080服务启动了...");
            // 开始无限接收请求
            while (true){
                Socket socket = serverSocket.accept();
                System.err.println(socket.getInetAddress().getHostName()+"连接成功");
                // 连接成功后可以开始处理IO流
                pool.execute(()->{
                    handler.handle(socket);
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //  IO处理器接口
    interface ISocketHandler{
        void handle(Socket socket);
    }

    // IO处理器实现
    class DefaultIOHandler implements ISocketHandler{
        @Override
        public void handle(Socket socket) {
            try{
                // 读取
                BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
                byte[] bytes = new byte[1024];
                int len = -1;
                while ((len=bis.read(bytes))!=-1){
                    System.out.println(new String(bytes,0,len));
                }
                socket.shutdownInput();
                // 回应
                BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
                bos.write("Operation successfully".getBytes(StandardCharsets.UTF_8));
                bos.flush();
                socket.shutdownOutput();
            }catch (IOException e){
                e.printStackTrace();
            }finally{
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }
}
